from django.http import Http404
from models import Content, MenuItem
from django.utils import translation

def items_from_menu(menu_name):
    return Content.objects.filter(menu_item__menu__name=menuname)

def get_content(path, menu_names=()):
    assert isinstance(path, basestring), 'path must be string'
    items = Content.objects
    if menu_names:
        subsets = [items.filter(menu_item__menu__name=m) for m in menu_names]
    else:
        subsets = [items]

    for subset in subsets:
        by_url = list(subset.filter(menu_item__url=path))
        if by_url:
            return by_url[0]
        by_named_url = [c for c in subset.exclude(menu_item__named_url='') if c.menu_item.get_url() == path]
        if by_named_url:
            return by_named_url[0]

    # if menu_item exists and content - no
    menu_item = get_menu_item(path, menu_names)
    if menu_item:
        c = Content(menu_item=menu_item)
        c.save()
        return c

    raise Http404, 'Content for path %s doesnt exists' % path
    #raise Exception, 'Content for path %s doesnt exists' % path

def get_menu_item(path, menu_names=()):
    items = MenuItem.objects
    if menu_names:
        subsets = [items.filter(menu__name=m) for m in menu_names]
    else:
        subsets = [items]
    for subset in subsets:
        by_url = list(subset.filter(url=path))
        if by_url:
            return by_url[0]
        by_named_url = [m for m in subset.exclude(named_url='') if m.get_url() == path]
        if by_named_url:
            return by_named_url[0]
    return None
